﻿using Dm;
using DMS.Common.Helper;
using DMS.Common.Model.Result;
using Google.Protobuf.WellKnownTypes;
using SqlSugar.Template.IService;
using SqlSugar.Template.IService.Param;
using SqlSugar.Template.IService.Result;
using SqlSugar.Template.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace SqlSugar.Template.Service
{
    public class BookService : BaseService<BookEntry>, IBookService
    {
        public async Task<ResponseResult> Add(AddBookParam param)
        {
            ResponseResult result = new();
            if (param == null
                ||param.UserId<0
                )
            {
                result.errno = 1;
                result.errmsg = "参数错误";
                return result;
            }
            BookEntry bookEntity = new()
            {
                UserId = param.UserId,
                Total = param.Total,
                Position = param.Position,
                ProfitAndLoss = param.ProfitAndLoss,
                ProfitAndLossRatio = param.ProfitAndLossRatio,
                PopularThemes = param.PopularThemes,
                TodayReview = param.TodayReview,
                TomorrowPlan = param.TomorrowPlan,
                Notes = param.Notes,
                Uri = param.Uri
            };

            //插入返回自增列
            var flag = await base.InsertReturnIdentityAsync(bookEntity);
            //null 列不插入
            flag = await base.AsInsertable(bookEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            result.data = flag;
            return result;
        }

        public async Task<ResponseResult> AddTran(AddBookParam param)
        {
            ResponseResult result = new();
            if (param == null
                || param.UserId < 0)
            {
                result.errno = 1;
                result.errmsg = "参数错误";
                return result;
            }
            BookEntry bookEntity = new()
            {
                UserId = param.UserId,
                Total = param.Total,
                Position = param.Position,
                ProfitAndLoss = param.ProfitAndLoss,
                ProfitAndLossRatio = param.ProfitAndLossRatio,
                PopularThemes = param.PopularThemes,
                TodayReview = param.TodayReview,
                TomorrowPlan = param.TomorrowPlan,
                Notes = param.Notes,
                Uri = param.Uri,
                StockId = param.StockId             
            };
            var Id = -1;
            #region 事物写法1
            var resultTran = await Context.Ado.UseTranAsync(async () =>
            {
                Id = await Context.Insertable(bookEntity).ExecuteReturnIdentityAsync();

            });
            if (!resultTran.IsSuccess)
            {
                //捕捉异常
                throw resultTran.ErrorException;
            }
            #endregion
            result.data = Id;
            return result;
        }

        public async Task<ResponseResult> DeleteAsync(long BookId)
        {
            ResponseResult result = new();
            var t1 = await Context.Deleteable<BookEntry>()
                .Where(a => a.Id == BookId)
                .ExecuteCommandAsync();
            result.data = t1;
            return result;
        }

        public async Task<ResponseResult<BookResult>> GetBookAsync(long Id)
        {
            ResponseResult<BookResult> result = new() { data = new BookResult() };
            var entity = await Context.Queryable<BookEntry>()
                .Select<BookResult>()
                .FirstAsync(q => q.StockId == Id);
            if (entity == null)
            {
                result.errno = 1;
                result.errmsg = "未找到相关数据";
                return result;
            }
            result.data = entity;
            return result;
        }

        public async Task<ResponseResult<PageModel<BookResult>>> SearchBookAsync(SearchBookParam param)
        {
            ResponseResult<PageModel<BookResult>> result = new()
            {
                data = new PageModel<BookResult>()
            };
            bool isEmpty = param.CreationTime == DateTime.MinValue;

            RefAsync<int> totalCount = 0;
            var expression = Expressionable.Create<BookEntry>();

            if (isEmpty)
            {
                expression.And(m => m.UserId == param.UserId);
                Expression<Func<BookEntry, bool>> where = expression.ToExpression();
                param.pageIndex = 1;
                result.data = await base.QueryPageList<BookResult>(where, param, "id desc");
              
            }
            //else if (!string.IsNullOrWhiteSpace(param.ClosingCode) || !string.IsNullOrWhiteSpace(param.StockCode))
            //{

            //    expression.AndIF(m => !string.IsNullOrWhiteSpace(param.ClosingCode),m=>m.c);
            //    Expression<Func<BookEntry, bool>> where = expression.ToExpression();
            //    result.data = await base.QueryPageList<BookResult>(where, param, "id desc");
            //}
            else
            {
                expression.And(m => m.CreationTime >= param.CreationTime && m.CreationTime <= param.CreationTime);
                expression.And(m => m.UserId == param.UserId);
                Expression<Func<BookEntry, bool>> where = expression.ToExpression();
                result.data = await base.QueryPageList<BookResult>(where, param, "id desc");
            }


            return result;

        }

        public async Task<ResponseResult> UpdateAsync(EditBookParam param)
        {
            ResponseResult result = new();
            if (param.Id <= 0)
            {
                result.errno = 1;
                result.errmsg = "参数不合法";
                return result;
            }
            var t1 = await Context.Updateable(
                new BookEntry()
                {
                    ModifyTime = DateTime.Now,
                    Total = param.Total,
                    Position = param.Position,
                    ProfitAndLoss = param.ProfitAndLoss,
                    ProfitAndLossRatio = param.ProfitAndLossRatio,
                    PopularThemes = param.PopularThemes,
                    TodayReview = param.TodayReview,
                    TomorrowPlan = param.TomorrowPlan,
                    Notes = param.Notes,
                    Uri = param.Uri,
                    StockId = param.StockId
                })
                .Where(a => a.Id == param.Id)
                .ExecuteCommandAsync();
            result.data = t1;
            return result;
        }
    }
}
